package com.learn.user.rest.api;

import java.util.UUID;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.learn.product.dto.ResultDTO;
import com.learn.product.util.ResultDTOUtil;
import com.learn.user.entity.UserInfo;
import com.learn.user.service.UserInfoService;
import com.learn.user.util.CookieUtil;

@RestController
@RequestMapping("login")
public class UserInfoApi {

	@Autowired
	private UserInfoService userInfoService;
	
//	@Autowired
//	private StringRedisTemplate redisTemplate;

	@PostMapping("buyer")
	public ResultDTO<?> buyer(@RequestParam("openid") String openid, HttpServletRequest request, HttpServletResponse response) {
		UserInfo userInfo = userInfoService.findByopenid(openid);
		if(userInfo == null) return ResultDTOUtil.error(400, "用户不存在");
		if(userInfo.getRole() != 2) return ResultDTOUtil.error(400, "权限不足");
		CookieUtil.setCookie(response, "openid", "abc", 7200);
		return ResultDTOUtil.success(userInfo);
	}

	@PostMapping("saller")
	public ResultDTO<?> saler(@RequestParam("openid") String openid, HttpServletRequest request, HttpServletResponse response) {
		Cookie cookie = CookieUtil.getCookie(request, "openid");
		if(cookie!=null && cookie.getValue().equals("xyz")) return ResultDTOUtil.success();
		UserInfo userInfo = userInfoService.findByopenid(openid);
		if(userInfo == null) return ResultDTOUtil.error(400, "用户不存在");
		if(userInfo.getRole() != 1) return ResultDTOUtil.error(400, "权限不足");
		String token = UUID.randomUUID().toString();
//		redisTemplate.opsForValue().set(String.format("TOKEN_USER_%s", token), userInfo.getOpenid(),7200,TimeUnit.SECONDS);
		CookieUtil.setCookie(response, "token", token, 7200);
		return ResultDTOUtil.success(userInfo);
	}
}
